package org.websocket;

import org.easy.ssh.EasyWebSshOperator;
import org.easy.ssh.IEasyWebSshOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.web.socket.*;

import java.nio.ByteBuffer;

/**
 * @Description: WebSSH的WebSocket处理器
 * @Author: wxl
 * @CreateTime: 2023/2/15 13:22
 */
public class EasyWebSshWebSocketHandler implements WebSocketHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(EasyWebSshWebSocketHandler.class);

    private final IEasyWebSshOperator operator;

    public EasyWebSshWebSocketHandler () {
        this.operator = new EasyWebSshOperator();
    }

    @Override
    public void afterConnectionEstablished(@NonNull WebSocketSession session) throws Exception {
        LOGGER.info("用户:{},连接WebSSH", session.getAttributes().get(Constant.USER_UUID_KEY));
        this.operator.initConnection(session);
    }

    @Override
    public void handleMessage(@NonNull WebSocketSession session, @NonNull WebSocketMessage<?> message) throws Exception {
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            this.operator.recvHandler(textMessage.getPayload(),session);
        } else if (message instanceof BinaryMessage) {
            // 二进制命令
            BinaryMessage binaryMessage = (BinaryMessage) message;
            // 将二进制命令转成String
            ByteBuffer byteBuffer = binaryMessage.getPayload();
        }
    }

    @Override
    public void handleTransportError(@NonNull WebSocketSession session, @NonNull Throwable exception) throws Exception {
        LOGGER.error("传输数据错误:{}",exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull CloseStatus closeStatus) throws Exception {
        this.operator.close(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
